import {save} from "@tauri-apps/api/dialog";
import {BaseDirectory, exists, readTextFile, writeTextFile} from "@tauri-apps/api/fs";


//文件操作
class FsUtils {

    /**
     *
     * @param name 文件名称
     * @param context 内容
     */
    async getFilePath(name: string) {
        const filePath = await save({
            filters: [{
                name: name,
                extensions: ['md']
            }]
        });
        if (filePath == null) return;
        return filePath;
    }

    /**
     *
     * @param filePath 文件路径
     */
    async readTextFile(filePath: string): Promise<string> {
        let result = await this.existsFile(filePath)
        if (!result) throw "文件路径错误"
        const text = await readTextFile(filePath, {dir: BaseDirectory.AppConfig});
        return text
    }

    /**
     * 写入文件
     * @param filePath
     * @param context
     */
    async writeTextFile(filePath: string, context: string) {
        return await writeTextFile(filePath, context, {dir: BaseDirectory.AppConfig});
    }

    /**
     *
     * @param filePath 文件路径
     */
    async existsFile(filePath: string): Promise<boolean> {
        const flg = await exists(filePath, {dir: BaseDirectory.AppData});
        return flg
    }


}

export default new FsUtils();